package com.huawei.demo;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.http.FormDataFilePart;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.core.utils.JsonUtils;
import com.huaweicloud.sdk.koomessage.v1.KooMessageClient;
import com.huaweicloud.sdk.koomessage.v1.model.CreatePubFastappModel;
import com.huaweicloud.sdk.koomessage.v1.model.CreatePubInfoRequest;
import com.huaweicloud.sdk.koomessage.v1.model.CreatePubInfoRequestBody;
import com.huaweicloud.sdk.koomessage.v1.model.CreatePubInfoResponse;
import com.huaweicloud.sdk.koomessage.v1.model.ExtMsg;
import com.huaweicloud.sdk.koomessage.v1.model.ListMenusRequest;
import com.huaweicloud.sdk.koomessage.v1.model.ListMenusResponse;
import com.huaweicloud.sdk.koomessage.v1.model.ListPortalInfosRequest;
import com.huaweicloud.sdk.koomessage.v1.model.ListPortalInfosResponse;
import com.huaweicloud.sdk.koomessage.v1.model.ListPubInfosRequest;
import com.huaweicloud.sdk.koomessage.v1.model.ListPubInfosResponse;
import com.huaweicloud.sdk.koomessage.v1.model.MenuInfoRequestBody;
import com.huaweicloud.sdk.koomessage.v1.model.MenuItem;
import com.huaweicloud.sdk.koomessage.v1.model.MenusMode;
import com.huaweicloud.sdk.koomessage.v1.model.MenusRsp;
import com.huaweicloud.sdk.koomessage.v1.model.PortalInfoRequestBody;
import com.huaweicloud.sdk.koomessage.v1.model.PortalModel;
import com.huaweicloud.sdk.koomessage.v1.model.PubInfoRequestBody;
import com.huaweicloud.sdk.koomessage.v1.model.PushMenuInfoRequest;
import com.huaweicloud.sdk.koomessage.v1.model.PushMenuInfoResponse;
import com.huaweicloud.sdk.koomessage.v1.model.PushPortalInfoRequest;
import com.huaweicloud.sdk.koomessage.v1.model.PushPortalInfoResponse;
import com.huaweicloud.sdk.koomessage.v1.model.TelModel;
import com.huaweicloud.sdk.koomessage.v1.model.UploadMediaRequest;
import com.huaweicloud.sdk.koomessage.v1.model.UploadMediaRequestBody;
import com.huaweicloud.sdk.koomessage.v1.model.UploadMediaResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

public class SaRegisterPortalTest {
    private static final Logger logger = LoggerFactory.getLogger(SaRegisterPortalTest.class);

    public static void main(String[] args) {
        String ak = "<YOUR AK>";
        String sk = "<YOUR SK>";
        BasicCredentials credentials = new BasicCredentials()
            .withAk(ak).withSk(sk);

        HttpConfig config = HttpConfig.getDefaultHttpConfig().withIgnoreSSLVerification(true);
        KooMessageClient kmClient = KooMessageClient.newBuilder()
            .withCredential(credentials)
            .withEndpoint("koomessage.myhuaweicloud.com")
            .withHttpConfig(config)
            .build();
        // 上传授权文件 授权文件为上传资源返回id
        String authFilePath = "{YOUR AUTHFILE PATH}";
        String authorizationFileId = uploadMedia(kmClient,authFilePath);
        List<String> authorizationFiles = new ArrayList<>();
        authorizationFiles.add(authorizationFileId);
        // 上传logo
        String logoPath = "{YOUR IMAGE PATH}";
        String logoImg = uploadMedia(kmClient,logoPath);
        // 上传背景图
        String backgroundImgPath = "{YOUR IMAGE PATH}";
        String backgroundImg = uploadMedia(kmClient,backgroundImgPath);
        // 上传快应用logo
        String fastLogoPath = "{YOUR IMAGE PATH}";
        String fastAppLogoImg = uploadMedia(kmClient,fastLogoPath);
        // 创建服务号
        CreatePubInfoResponse createPubInfoResponse = createPub(kmClient,authorizationFiles,logoImg,backgroundImg,fastAppLogoImg);
        // 查询服务号列表（可查看服务号是否生效）
        ListPubInfosResponse listPubInfosResponse = listPubInfos(kmClient);
        System.out.println(JsonUtils.toJSON(listPubInfosResponse));

        // 催审主页（可选，服务号生效后可催审主页）
        // 主页id
        assert createPubInfoResponse != null;
        String portalId = createPubInfoResponse.getData().getData().getPortalId();
        // 查询主页列表
        ListPortalInfosResponse listPortalInfosResponse = listPortalInfos(kmClient);
        assert listPortalInfosResponse != null;
        List<PortalModel> portalModelList = listPortalInfosResponse.getData().getPortals();
        // 遍历主页列表，判断服务号主页是否审核通过，待审核的主页可以催审，从主页列表listPortalInfos获取审核状态判断
        for (PortalModel portalModel : portalModelList) {
            // approve_state 值1表示待审核
            if (portalId.equals(portalModel.getPortalId()) && portalModel.getApproveState() == 1) {
                // 催审主页
                pushPortal(kmClient,portalId);
            }
        }

        // 催审菜单（可选，服务号生效后可催审菜单）
        // 查询菜单列表
        ListMenusResponse listMenus = listMenus(kmClient);
        // 创建服务号返回的菜单id
        String menuId = createPubInfoResponse.getData().getData().getMenuId();
        assert listMenus != null;
        List<MenusRsp> menusRspList = listMenus.getData().getData();
        for (MenusRsp menusRsp : menusRspList) {
            // 未生效的菜单可以催审，从菜单列表listMenus获取菜单状态判断
            if (menuId.equals(menusRsp.getMenuId()) && menusRsp.getMenuState() == 1) {
                // 催审菜单
                pushMenuInfo(kmClient,menuId);
            }
        }
    }

    /**
     * 上传服务号图片资源
     *
     * @param kmClient  请求客户端
     * @param path      路径
     */
    public static String uploadMedia(KooMessageClient kmClient,String path) {
        try {
            UploadMediaRequest request = new UploadMediaRequest();
            UploadMediaRequestBody body = new UploadMediaRequestBody();
            // 图片地址如  D:\\test.png
            File file = new File(path);
            FileInputStream fileInputStream = new FileInputStream(file);
            // test.png可替换为对应资源的名称
            FormDataFilePart formDataFilePart = new FormDataFilePart(fileInputStream,"test.png");
            body.setFile(formDataFilePart);
            body.setFileType("OTHER");
            request.setBody(body);
            UploadMediaResponse response = kmClient.uploadMedia(request);
            System.out.println(JsonUtils.toJSON(response));
            return response.getData().getResourceId();
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return null;
    }

    /**
     * 一站式创建服务号
     *
     * @param kmClient      请求客户端
     * @param authorizationFiles    授权文件
     * @param logoImg       logo
     * @param backgroundImg     背景图
     * @param fastAppLogoImg    快应用logo
     */
    public static CreatePubInfoResponse createPub(KooMessageClient kmClient,List<String> authorizationFiles,String logoImg,String backgroundImg,String fastAppLogoImg) {
        try {
            CreatePubInfoRequest request = new CreatePubInfoRequest();

            CreatePubInfoRequestBody body = new CreatePubInfoRequestBody();
            // 服务号body
            PubInfoRequestBody pubInfoRequestBody = new PubInfoRequestBody();

            List<String> signsForAuthGetPort = new ArrayList<>();
            // 设置服务号信息（图标使用上传服务号图片资源返回的id）
            pubInfoRequestBody.withLogoImg(logoImg).withAuthorizationFiles(authorizationFiles);
            pubInfoRequestBody.withPubName("服务号名称").withPubAbstract("服务号摘要").withPubRemark("服务号备注")
                .withAutoGetPort(0).withIndustry(1).withSignsForAutoGetPort(signsForAuthGetPort);

            // 设置主页内容
            PortalInfoRequestBody portalInfoRequestBody = new PortalInfoRequestBody();
            // 热线号列表
            List<TelModel> tels = new ArrayList<>();
            TelModel telModel = new TelModel();
            telModel.withTel("131****0000").withUsage("官网电话用途");
            tels.add(telModel);
            // 快应用列表
            List<CreatePubFastappModel> fastApps = new ArrayList<>();
            CreatePubFastappModel createPubFastappModel = new CreatePubFastappModel();
            createPubFastappModel.withName("主页快应用").withDeeplink("{YOUR DEEP LINK}").withLogoImg(fastAppLogoImg)
                .withDescription("快应用简介").withDependEngineVersion("1040");
            fastApps.add(createPubFastappModel);
            // 华为服务号列表
            List<String> hwPubs = new ArrayList<>();
            // 设置主页 背景图、简介、热线号、快应用、华为服务号列表
            // 背景图为上传图片资源接口返回id
            portalInfoRequestBody.withBackgroundImg(backgroundImg).withSummary("主页简介")
                .withTels(tels).withFastapps(fastApps).withHwPubs(hwPubs);

            // 设置菜单内容
            MenuInfoRequestBody menuInfoRequestBody = new MenuInfoRequestBody();
            ExtMsg extMsg = new ExtMsg();
            extMsg.withWebTitle("标题").withOpenInBrowser("1");
            // 菜单为跳转链接时子菜单列表为空
            List<MenuItem> subMenuItems = new ArrayList<>();
            MenuItem menuItem = new MenuItem();
            List<MenuItem> menuItems = new ArrayList<>();
            menuItem.withName("打开商城").withActionType("OPEN_URL").withContent("{YOUR URL}")
                .withExtMsg(extMsg).withSubMenuItems(subMenuItems);
            menuItems.add(menuItem);

            MenusMode menusMode = new MenusMode();
            menusMode.setMenuItems(menuItems);
            menuInfoRequestBody.setMenu(menusMode);

            body.withPubRequestBody(pubInfoRequestBody).withPortalRequestBody(portalInfoRequestBody)
                .withMenuRequestBody(menuInfoRequestBody);
            request.setBody(body);
            return kmClient.createPubInfo(request);
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return null;
    }


    /**
     * 查询服务号列表
     *
     * @param kmClient  请求客户端
     */
    public static ListPubInfosResponse listPubInfos(KooMessageClient kmClient) {
        try {
            ListPubInfosRequest request = new ListPubInfosRequest();
            request.setLimit(10);
            request.setOffset(0);
            return kmClient.listPubInfos(request);
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return null;
    }

    /**
     * 催审主页
     *
     * @param kmClient  请求客户端
     * @param portalId 主页id
     */
    public static void pushPortal(KooMessageClient kmClient,String portalId) {
        try {
            PushPortalInfoRequest request = new PushPortalInfoRequest();
            // 对应主页的id
            request.setPortalId(portalId);
            PushPortalInfoResponse response = kmClient.pushPortalInfo(request);
            System.out.println(JsonUtils.toJSON(response));
        } catch (Exception e) {
            logger.error(e.toString());
        }
    }

    /**
     * 催审菜单
     *
     * @param kmClient  请求客户端
     * @param menuId    菜单id
     */
    public static void pushMenuInfo(KooMessageClient kmClient,String menuId) {
        try {
            PushMenuInfoRequest request = new PushMenuInfoRequest();
            // 替换为要催审的菜单id，可通过菜单列表获取
            request.setMenuId(menuId);
            PushMenuInfoResponse response = kmClient.pushMenuInfo(request);
            System.out.println(response);
        } catch (Exception e) {
            logger.error(e.toString());
        }
    }

    /**
     * 查询主页列表
     *
     * @param kmClient  请求客户端
     */
    public static ListPortalInfosResponse listPortalInfos(KooMessageClient kmClient) {
        try {
            ListPortalInfosRequest request = new ListPortalInfosRequest();
            request.setLimit(100);
            request.setOffset(0);
            ListPortalInfosResponse response = kmClient.listPortalInfos(request);
            System.out.println(response);
            return response;
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return null;
    }

    /**
     * 查询菜单列表
     *
     * @param kmClient  请求客户端
     */
    public static ListMenusResponse listMenus(KooMessageClient kmClient) {
        try {
            ListMenusRequest request = new ListMenusRequest();
            request.setLimit(10);
            request.setOffset(0);
            ListMenusResponse response = kmClient.listMenus(request);
            System.out.println(response);
            return response;
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return null;
    }
}
